package com.pb.wkflow.core.factor.behavior;

import com.pb.infra.oth.util.SpringContextUtil;
import com.pb.wkflow.api.exception.ApprovalException;
import com.pb.wkflow.core.entity.PostInfo;
import com.pb.wkflow.core.service.UserParticipantService;
import com.pb.wkflow.core.utils.StringUtils;
import org.camunda.bpm.engine.impl.bpmn.behavior.UserTaskActivityBehavior;
import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity;
import org.camunda.bpm.engine.impl.persistence.entity.TaskEntity;
import org.camunda.bpm.engine.impl.pvm.delegate.ActivityExecution;
import org.camunda.bpm.engine.impl.task.TaskDecorator;
import org.camunda.bpm.model.bpmn.BpmnModelInstance;
import org.camunda.bpm.model.bpmn.impl.instance.UserTaskImpl;
import org.camunda.bpm.model.bpmn.instance.MultiInstanceLoopCharacteristics;
import org.camunda.bpm.model.xml.instance.ModelElementInstance;

import java.util.Collection;

/**
 * 用户节点解析行为
 * @author 苗益辉
 * @date 2022/5/20 14:19
 */
public class MyUserTaskActivityBehavior extends UserTaskActivityBehavior {

    public MyUserTaskActivityBehavior(TaskDecorator taskDecorator) {
        super(taskDecorator);
    }

    @Override
    public void performExecution(ActivityExecution execution) throws Exception {
        TaskEntity task = new TaskEntity((ExecutionEntity) execution);
        task.insert();
        BpmnModelInstance bpmnModelInstance = execution.getBpmnModelInstance();
        String id = execution.getCurrentActivityId();
        if(StringUtils.isBlank(id) || bpmnModelInstance == null) {
            throw new ApprovalException("activityId为空，请检查流程定义");
        }
        ModelElementInstance modelElementInstance = bpmnModelInstance.getModelElementById(id.split("#")[0]);
        UserTaskImpl userTask = (UserTaskImpl) modelElementInstance;
        Collection<MultiInstanceLoopCharacteristics> mls = userTask.getChildElementsByType(MultiInstanceLoopCharacteristics.class);
        if(!mls.isEmpty()) {
            MultiInstanceLoopCharacteristics characteristics = mls.iterator().next();
            String camundaElementVariable = characteristics.getCamundaElementVariable();
            Object variable = execution.getVariable(camundaElementVariable);
            if(variable instanceof PostInfo) {
                UserParticipantService userParticipantService = SpringContextUtil.getBean(UserParticipantService.class);
                userParticipantService.saveUserTaskAssignment(task, (PostInfo) variable);
            }else {
                throw new ApprovalException("会签对象不是PostInfo");
            }
        }
        taskDecorator.decorate(task, execution);
        task.transitionTo(TaskEntity.TaskState.STATE_CREATED);
    }

}
